<?php

namespace app\admin\controller;

use app\admin\model\order\Items;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Orders extends Backend
{

    protected $noNeedRight = ['details'];
    protected $noNeedLogin = ['details'];

    /**
     * Orders模型对象
     * @var \app\admin\model\Orders
     */
    protected $model = null;

    /**
     * Order_item 模型对象
     * @var Items
     */
    protected $orderItemModel = null;

    /**
     * Products 模型对象
     * @var \app\admin\model\Products
     */
    protected $productModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orders;
        $this->orderItemModel = new Items();
        $this->productModel = new \app\admin\model\Products();
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(["client"])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        //print_r($this->model->getLastSql());die();
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            if ($result) {
                // 保存订单明细
                $this->saveOrderItem($this->model->getLastInsID(), $params['product_id']);
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 订单明细
     * @return string
     * @throws \think\Exception
     */
    function details()
    {
        $orderid = $this->request->param('ids');
        $sql = "select p.product_name, item.quantity, item.unit_price, fo.order_no
from fa_order_items as item
         left join fa_products as p on item.product_id = p.id
        left join fa_orders fo on item.order_id = fo.order_id
where item.order_id = {$orderid}";
        $rst = Db::query($sql);
        $this->assign('orderNo', $rst[0]['order_no']??'');
        $this->assign('orderId', $orderid);
        $this->assign('orderItemList', $rst);
        return $this->view->fetch();
    }

    function saveOrderItem($order_id, $product_id){

        Db::startTrans();
        try{
        // 根据Product_id 查询 产品的价格
        $product = $this->productModel-> where('id', '=', $product_id) -> find();
        // 保存到 order_item 表中
        $itemData = [
            'order_id' =>$order_id,
            'product_id' => $product_id,
            'quantity' => 1,
            'unit_price' => $product->price,
        ];

        $result = $this->orderItemModel->save($itemData);
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        return $result;
    }

}
